package sy.service.impl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sy.dao.ApkDaoI;
import sy.model.Tapk;
import sy.pageModel.DataGrid;
import sy.pageModel.PageHelper;
import sy.service.ApkServiceI;

import java.util.*;

@Service
public class ApkServiceImpl implements ApkServiceI {
	@Autowired
	private ApkDaoI apkDao;
	
	@Override
	public void delete(String id) {
        apkDao.delete(apkDao.get(Tapk.class, id));
	}

	@Override
	public void add(Tapk tapk) throws Exception {
        Tapk u = new Tapk();

		u.setId(UUID.randomUUID().toString());
        u.setCreatetiem(tapk.getCreatetiem());
        u.setFilename(tapk.getFilename());
        u.setFilepath(tapk.getFilepath());
        u.setVersion(tapk.getVersion());
        apkDao.save(u);
	}
	@Override
    public void update(Tapk tapk){
        apkDao.update(tapk);
    }
	private String orderHql(PageHelper ph) {
		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}
	@Override
	public DataGrid dataGrid(Tapk tapk, PageHelper ph) {
		DataGrid dg = new DataGrid();
		List<Tapk> ul = new ArrayList<Tapk>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tapk t ";
		List<Tapk> l = apkDao.find(hql + whereHql(tapk, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
		if (l != null && l.size() > 0) {
			for (Tapk t : l) {
                Tapk u = new Tapk();
				BeanUtils.copyProperties(t, u);
				ul.add(u);
			}
		}
		dg.setRows(ul);
		dg.setTotal(apkDao.count("select count(*) " + hql + whereHql(tapk, params), params));
		return dg;
	}
	private String whereHql(Tapk tapk, Map<String, Object> params) {
		String hql = "";
		if (tapk != null) {
			hql += " where 1=1 ";
			if (tapk.getVersion() != null) {
                hql += " and t.version like :version";
                params.put("version", "%%" + tapk.getVersion() + "%%");
            }
			if (tapk.getFilename() != null) {
				hql += " and t.filename like :filename";
				params.put("filename", "%%" + tapk.getFilename() + "%%");
			}
		}
		return hql;
	}

	@Override
	public List<Tapk> getapks() {
		
		String hql = " from Tapk t ";
		List<Tapk> l = apkDao.find(hql);
		
		return l;
	}
    @Override
    public Tapk get(String id){
        String hql = " from Tapk t where t.id= '"+id+"'";
        List<Tapk> l = apkDao.find(hql);
        if(l!=null&&l.size()>0){
            return l.get(0);
        }
        return null;
    }
    @Override
    public Tapk getLastTapk(){
        String hql = " from Tapk t order by t.createtiem desc ";
        List<Tapk> l = apkDao.find(hql);
        if(l.size()>0){
            return l.get(0);
        }
        return null;
    }
}
